# == Coding: UTF-8 ==
# @Project :        DormitoryManagementSystem
# @fileName         register.py
# @version          v0.5
# @author           16980
# @GiteeWarehouse   https://gitee.com/liu-long068/
# @WritingTime      2023/5/1 0001
# @Software:        PyCharm
# ====/******/=====
import hashlib
import json


class Register:
    def __init__(self):
        self.users = []
        self.path = r'D:\BooksManagementSystem\public\users\users.json'
        self.username = None
        self.password = None
        self.status = None
        self.load_users()

    def load_users(self):
        # 先读取已有的 JSON 文件
        try:
            with open(self.path, 'r') as file:
                self.users = json.load(file)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f'Error loading user data: {e}')

    def save_users(self):
        try:
            with open(self.path, 'w') as file:
                json.dump(self.users, file, ensure_ascii=False, indent=4)
        except FileNotFoundError as e:
            print(f'Error saving user data: {e}')

    def register_business(self):
        self.username = input('注册用户名：')
        if self.username in [user['username'] for user in self.users]:
            print("用户名已存在！")
            return False

        if not (6 <= len(self.username) <= 20):
            print("用户名长度必须为6~20位！")
            return False

        password = input('注册密码：')
        confirm_password = input('确认注册密码：')
        if not (8 <= len(password) <= 30):
            print("密码长度必须为8~30位！")
            return False

        if password != confirm_password:
            print("确认注册密码和密码不一致！")
            return False

        hashed_password = hashlib.sha256(password.encode()).hexdigest()
        new_user = {
            'username': self.username,
            'password': hashed_password,
            'flag': 2
        }
        self.users.append(new_user)
        self.save_users()
        print(f"用户注册成功！账号：{self.username}, 密码为：【{password}】!")
        return True
